package com.itheima.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author Xiao
 * @date 2021/8/31
 */
public class SqlSessionFactoryUtils {
    //成员变量：提升作用域
    private static SqlSessionFactory sqlSessionFactory;
    //静态代码块：随着类的加载而加载，只加载一次
    static {
        try {
            String s = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(s);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSqlSession() {
        //获取自动提交的SqlSession对象
        //return sqlSessionFactory.openSession(true);
        //获取手动提交的SqlSession对象   提交方法：commit()
        return sqlSessionFactory.openSession();
    }
}
